package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.dao.KwWxSubscribeDao;
import com.meirengu.webview.model.KwWxSubscribe;
import com.meirengu.webview.service.KwOperationLogService;
import com.meirengu.webview.service.XjWxSubscribeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class XjWxSubscribeServiceImpl extends BaseServiceImpl<KwWxSubscribe> implements XjWxSubscribeService {


    @Autowired
    RedisClient redisClient;

    @Autowired
    ProducerBean producer;

    @Autowired
    private KwWxSubscribeDao kwWxSubscribeDao;

    @Autowired
    private KwOperationLogService kwOperationLogService;

    Logger logger = LoggerFactory.getLogger(XjWxSubscribeServiceImpl.class);

    @Override
    public void wxAccessToken() throws Exception {
        String accessToken = "";
        /*HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c09d7bf83d9b8f2&secret=3c6667228c17dd595f69dfb45d098d2b");*/
        HttpUtil.HttpResult hr = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7c42ba83e1517fa1&secret=692972f8ed9a8123cba6e0dff78b7496");
        int code = hr.getStatusCode();
        logger.info("hr:{}" + hr.toString());
        if (code == 200) {
            logger.info("==wxAccessToken http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            accessToken = returnMsg.getString("access_token");
            redisClient.set("XJWXACCESSTOKEN", accessToken);
        } else {
            logger.warn("==wxAccessToken http requesst fail. code:{}, result:{}", code, hr.toString());
        }
    }

    @Override
    public void createMenu() throws Exception {
        JSONObject jsonObject = new JSONObject();
        JSONArray button = new JSONArray();
        JSONObject button1 = new JSONObject();//我要贷款
        JSONObject button2 = new JSONObject();//帮你借
        JSONObject button3 = new JSONObject();//大额借款

        button1.put("type", "view");
        button1.put("name", "⚡秒下款");
        button1.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg2#/market");
        button.add(button1);

        button2.put("type", "click");
        button2.put("name", "\uD83D\uDCB0帮你借");
        button2.put("key", "CLICK_HELP_LOAN");
        button.add(button2);

        button3.put("type", "view");
        button3.put("name", "\uD83D\uDD25大额借款");
        button3.put("url", "https://mdzj139.com/loan/?cid=channel_wxtg2");
        button.add(button3);
        jsonObject.put("button", button);


        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + redisClient.get("XJWXACCESSTOKEN");
        HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
        System.out.println(hr.toString());
    }

    @Override
    public void getUserList() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + redisClient.get("XJWXACCESSTOKEN");
        /*String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=14_XtlAFIKufRItmgnngj9qi00aSvVEgANRktePBLaPct5jQ0okZpNY4IvZN5AQ1LqasQAeITrFAbKOp4upvySBq7KMbz8ETIhAOovNTY4YLPfSn3UWYkPR6cmXkbD822v0fnSuWsGQzt5nrO9aTSNbAEALKF";*/
        HttpUtil.HttpResult hr = HttpUtil.doGet(url);
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==getUserList http requesst success. result:{}", code, hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            JSONObject data = returnMsg.getJSONObject("data");
            JSONArray openidAry = data.getJSONArray("openid");
            String toUserName = "gh_275fb62605e0";
            String openid = null;
            //校验是否已订阅
            Map<String, Object> params = new HashMap<>();
            Integer count = null;
            KwWxSubscribe kwWxSubscribe = null;
            for (int i = 0; i < openidAry.size(); i++) {
                openid = openidAry.getString(i);
                params.put("fromUserName", openid);
                params.put("toUserName", toUserName);
                count = kwWxSubscribeDao.getCount(params);
                //已有推送记录
                if (!NumberUtil.isNullOrZero(count)) {
                    System.out.println("已有订阅");
                    continue;
                }
                String userUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + redisClient.get("XJWXACCESSTOKEN") + "&openid=" + openid + "&lang=zh_CN";
                HttpUtil.HttpResult hr1 = HttpUtil.doGet(userUrl);
                String content1 = new String(hr1.getContent().getBytes("ISO-8859-1"), "UTF-8");
                logger.info("content1:{}" + content1);
                JSONObject jsonObject = JSONObject.parseObject(content1);
                String nikeName = jsonObject.getString("nickname");
                kwWxSubscribe = new KwWxSubscribe();
                kwWxSubscribe.setToUserName(toUserName);
                kwWxSubscribe.setFromUserName(openid);
                kwWxSubscribe.setCreateTime(new Date());
                kwWxSubscribe.setMsgType("event");
                kwWxSubscribe.setEvent("subscribe");
                kwWxSubscribe.setNikeName(nikeName);
                insert(kwWxSubscribe);
            }
        } else {
            logger.warn("==XJWXACCESSTOKEN http requesst fail. code:{}, result:{}", code, hr.toString());
        }
    }

    @Override
    public void sendTemplateMsg(String name) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> map = new HashMap<>();
        map.put("toUserName", "gh_275fb62605e0");
        List<Map<String, Object>> userList = getList(map);
        String openid = null;
        JSONObject dataJson = null;
        JSONObject first = null;
        JSONObject keyword1 = null;
        JSONObject keyword2 = null;
        JSONObject keyword3 = null;
        JSONObject keyword4 = null;
        JSONObject keyword5 = null;
        JSONObject remark = null;
        kwOperationLogService.addOperationLog("2", "sendTemplateMsg", "发送香蕉有钱模板消息",
                name, sdf.format(new Date()), sdf.format(new Date()), "sendTemplateMsg", 0,
                null, null, null);
        for (Map<String, Object> userMap : userList) {
            openid = userMap.get("fromUserName").toString();
            jsonObject.put("touser", openid);
            jsonObject.put("template_id", "-qWPSul-tuejezm6CQmBeZXJAFqQnVTetzn-m9Xb528");
            jsonObject.put("url", "https://mdzj139.com/loan/index.html?cid=channel_wxtg2#/market");
            dataJson = new JSONObject();

            first = new JSONObject();
            first.put("value", "根据您的资质和情况，已符合贷款资格，额度1000-5000元");
            first.put("color", "#FF0000");
            dataJson.put("first", first);

            keyword1 = new JSONObject();
            keyword1.put("value", name);
            keyword1.put("color", "#173177");
            dataJson.put("keyword1", keyword1);

            keyword2 = new JSONObject();
            keyword2.put("value", "1000-5000元");
            keyword2.put("color", "#173177");
            dataJson.put("keyword2", keyword2);

            keyword3 = new JSONObject();
            keyword3.put("value", "7-30天");
            keyword3.put("color", "#173177");
            dataJson.put("keyword3", keyword3);

            remark = new JSONObject();
            StringBuilder contentBuffer = new StringBuilder();
            contentBuffer.append("点击立即申请>>>");
            String contentStr = contentBuffer.toString();
            remark.put("value", contentStr);
            remark.put("color", "#FF0000");
            dataJson.put("remark", remark);

            jsonObject.put("data", dataJson);

            /*String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=14_DhgdYNoEVjs2ajDbFpyrDF9V-Xaaq9GLd_iGYgocAWs_LyCMw0fDnjmV5ItLcrhUlnNnRqjoPZVdqH3w2QA4pa2mumB9gFuE_GnHifgXm_qPO7iCBwc4gPqtRCsHGRx4vIFL4oHUAzT-bS0FMVOfADAVEX";*/
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + redisClient.get("XJWXACCESSTOKEN");
            HttpUtil.HttpResult hr = HttpUtil.doPost(url, jsonObject.toString());
            System.out.println(hr.toString());
        }

    }
}
